<template>
  <div class="credit-setting-list">
    <a-card title="征信变量配置">
      <div class="search-form">
        <div class="form-content">
          <a-form-item label="中文名称">
            <a-input v-model="queryParam.chineseName" placeholder="请输入中文名称" style="width: 200px" allowClear />
          </a-form-item>
          <a-form-item label="英文名称">
            <a-input v-model="queryParam.englishName" placeholder="请输入英文名称" style="width: 200px" allowClear />
          </a-form-item>
          <div class="form-actions">
            <div class="all-actions">
              <div class="search-actions">
                <a-button type="primary" @click="searchHandle">查询</a-button>
                <a-button @click="resetHandle">重置</a-button>
              </div>
              <div class="operation-actions">
                <a-button type="primary" @click="handleAdd">添加</a-button>
              </div>
            </div>
          </div>
        </div>
      </div>
      <s-table
        ref="table"
        size="default"
        rowKey="id"
        :columns="columns"
        :data="loadData"
        :alert="false"
        showPagination="auto">
        <template slot="serialNumber" slot-scope="text, record, index">
          {{ (pagination.current - 1) * pagination.pageSize + index + 1 }}
        </template>
        <template slot="setCode" slot-scope="text, record">
          <a-button
            type="link"
            @click="handleVariableConfig(record)"
            style="padding: 0; height: auto; font-size: 14px;">
            {{ record.setCode }}
          </a-button>
        </template>
        <template slot="description" slot-scope="text, record">
          <a-tooltip>
            <template slot="title">{{ record.description }}</template>
            {{ record.description }}
          </a-tooltip>
        </template>
        <template slot="tags" slot-scope="text, record">
          <span v-if="record.tags">
            <a-tag v-for="tag in record.tags.split(',')" :key="tag" color="blue">
              {{ tag.trim() }}
            </a-tag>
          </span>
        </template>
        <template slot="createTime" slot-scope="text, record">
          {{ formatTime(record.gmtCreate) }}
        </template>
        <span slot="operation" slot-scope="text, record">
          <a-button type="link" @click="handleEdit(record)">编辑</a-button>
          <a-divider type="vertical" />
          <a-button type="link" @click="handleVariableConfig(record)">添加</a-button>
          <a-divider type="vertical" />
          <a-button type="link" @click="handleDelete(record)">删除</a-button>
        </span>
      </s-table>

      <!-- 新增/编辑弹窗 -->
      <credit-setting-modal
        :visible="modalVisible"
        :isEdit="isEdit"
        :currentRecord="currentRecord"
        @success="handleModalSuccess"
        @cancel="handleModalCancel" />
    </a-card>
  </div>
</template>

<script>
import { STable } from '@/components'
import moment from 'moment'
import { getBizList, getBizDelete, getBizCreate, getBizUpdate, getBizDetail } from '@/api/creditSetting'
import { mapGetters } from 'vuex'
import CreditSettingModal from './components/creditSetting.vue'

const columns = [
  // {
  //   title: '序号',
  //   width: 80,
  //   scopedSlots: { customRender: 'serialNumber' },
  // },
  {
    title: 'ID',
    dataIndex: 'id',
    width: 80,
  },
  {
    title: '变量集',
    dataIndex: 'setCode',
    width: 150,
    scopedSlots: { customRender: 'setCode' },
  },
  {
    title: '描述',
    dataIndex: 'description',
    width: 200,
    scopedSlots: { customRender: 'description' },
  },
  {
    title: '标签',
    dataIndex: 'tags',
    width: 180,
    scopedSlots: { customRender: 'tags' },
  },
  {
    title: '创建人',
    dataIndex: 'createdBy',
    width: 120,
  },
  {
    title: '创建时间',
    dataIndex: 'gmtCreate',
    width: 180,
    scopedSlots: { customRender: 'createTime' },
  },
  {
    title: '操作',
    scopedSlots: { customRender: 'operation' },
    width: 200,
    fixed: 'right',
  },
]

export default {
  name: 'CreditSettingList',
  components: {
    STable,
    CreditSettingModal
  },
  props: {},
  data() {
    return {
      columns,

      pagination: {
        total: 0,
        current: 1,
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: true,
      },
      queryParam: {
        setCode: '',
        description: '',
        tags: '',
      },
      modalVisible: false,
      confirmLoading: false,
      isEdit: false,
      currentRecord: null,
      formData: {
        setCode: '',
        description: '',
        tags: [''],
        createdBy: '',
      },
      rules: {
        setCode: [
          { required: true, message: '请输入变量集', trigger: 'blur' },
          { min: 2, max: 50, message: '变量集长度在 2 到 50 个字符', trigger: 'blur' },
        ],
        description: [
          { required: true, message: '请输入描述', trigger: 'blur' },
          { min: 2, max: 500, message: '描述长度在 2 到 500 个字符', trigger: 'blur' },
        ],
        tags: [
          { required: true, message: '请输入标签', trigger: 'blur' },
        ],
      },
    }
  },
  computed: {
    ...mapGetters(['nickname']),
    modalTitle() {
      return this.isEdit ? '编辑变量集' : '新增变量集'
    },
  },
  mounted() {
    // 页面加载时可以自动查询
  },
  methods: {
    getBizList,
    getBizDelete,
    getBizCreate,
    getBizUpdate,
    getBizDetail,
    handleTableChange(pagination) {
      this.$emit('change', pagination)
    },
    searchHandle() {
      this.$refs.table.refresh(true)
    },
    resetHandle() {
      this.queryParam = {
        setCode: '',
        description: '',
        tags: '',
      }
    },
    handleAdd() {
      this.isEdit = false
      this.currentRecord = null
      this.formData = {
        setCode: '',
        description: '',
        tags: [''],
        createdBy: '',
      }
      this.modalVisible = true
    },
    loadData(parameter) {
      const requestParameters = {
        current: parameter.pageNo || 1,
        pageSize: parameter.pageSize || 20,
        condition: {
          setCode: this.queryParam.setCode || '',
          description: this.queryParam.description || '',
          tags: this.queryParam.tags || '',
        },
        orderBy: ['id desc']
      }

      console.log('loadData request parameters:', requestParameters)
      return this.getBizList(requestParameters).then((res) => {
        if (res.code === 0 && res.data) {
          return {
            total: res.data.length,
            curPage: parameter.pageNo || 1,
            data: res.data || [],
            totalPage: Math.ceil(res.data.length / (parameter.pageSize || 20)),
            pageSize: parameter.pageSize || 20,
          }
        }
        return {
          total: 0,
          curPage: 1,
          data: [],
          totalPage: 0,
          pageSize: 20,
        }
      })
    },
    handleVariableConfig(record) {
      // 跳转到变量配置页面，传递变量集信息
      this.$router.push({
        path: '/model/creditSetting/variableConfig',
        query: {
          setCode: record.setCode,
          setId: record.id
        }
      })
    },
    handleEdit(record) {
      this.isEdit = true
      this.currentRecord = record
      this.modalVisible = true

      // 调用详情接口获取完整数据
      this.getBizDetail({ setCode: record.setCode })
        .then((res) => {
          if (res.code === 0 && res.data) {
            this.formData = {
              setCode: res.data.setCode || '',
              description: res.data.description || '',
              tags: res.data.tags ? res.data.tags.split(',').map(tag => tag.trim()) : [''],
              createdBy: res.data.createdBy || '',
            }
          } else {
            this.$message.error(res.message || '获取详情失败')
          }
        })
        .catch((error) => {
          console.error('获取详情失败:', error)
          this.$message.error('获取详情失败，请稍后重试')
        })
    },
    handleDelete(record) {
      this.$confirm({
        title: '确认删除',
        content: `确定要删除变量集"${record.setCode}"吗？`,
        onOk: () => {
          this.getBizDelete({ setCode: record.setCode })
            .then((res) => {
              if (res.code === 0) {
                this.$message.success('删除成功')
                this.$refs.table.refresh()
              } else {
                this.$message.error(res.message || '删除失败')
              }
            })
            .catch((error) => {
              console.error('删除变量集失败:', error)
              this.$message.error('删除失败，请稍后重试')
            })
        },
      })
    },
    formatTime(time) {
      if (!time) return ''
      return moment(time).format('YYYY-MM-DD HH:mm:ss')
    },
    handleModalOk() {
      // 手动验证表单
      if (!this.formData.setCode || !this.formData.setCode.trim()) {
        this.$message.error('请输入变量集')
        return
      }
      if (!this.formData.description || !this.formData.description.trim()) {
        this.$message.error('请输入描述')
        return
      }
      // 验证标签
      const validTags = this.formData.tags.filter(tag => tag && tag.trim())
      if (validTags.length === 0) {
        this.$message.error('请至少输入一个标签')
        return
      }
      if (this.formData.setCode.length < 2 || this.formData.setCode.length > 50) {
        this.$message.error('变量集长度在 2 到 50 个字符')
        return
      }
      if (this.formData.description.length < 2 || this.formData.description.length > 500) {
        this.$message.error('描述长度在 2 到 500 个字符')
        return
      }

      this.confirmLoading = true
      const params = {
        ...this.formData,
        tags: this.formData.tags.filter(tag => tag && tag.trim()).join(','),
        createdBy: this.isEdit ? this.formData.createdBy : this.nickname,
      }

      if (this.isEdit && this.currentRecord) {
        params.id = this.currentRecord.id
      }

      const apiMethod = this.isEdit ? this.getBizUpdate : this.getBizCreate

      apiMethod(params)
        .then((res) => {
          if (res.code === 0) {
            this.$message.success(this.isEdit ? '编辑成功' : '新增成功')
            this.modalVisible = false
            this.$refs.table.refresh()
          } else {
            this.$message.error(res.message || (this.isEdit ? '编辑失败' : '新增失败'))
          }
        })
        .catch((error) => {
          console.error('操作失败:', error)
          this.$message.error(this.isEdit ? '编辑失败，请稍后重试' : '新增失败，请稍后重试')
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
    handleModalSuccess() {
      this.modalVisible = false
      this.$refs.table.refresh()
    },
    handleModalCancel() {
      this.modalVisible = false
      this.confirmLoading = false
      // 手动重置表单数据
      this.formData = {
        setCode: '',
        description: '',
        tags: [''],
        createdBy: '',
      }
    },
    addTag() {
      this.formData.tags.push('')
    },
    removeTag(index) {
      if (this.formData.tags.length > 1) {
        this.formData.tags.splice(index, 1)
      }
    },
  }
}
</script>

<style lang="less" scoped>
.credit-setting-list {

  .search-form {
    margin-bottom: 16px;
    padding: 12px 16px;
    background: #fafafa;
    border-radius: 6px;
  }

  .form-content {
    display: flex;
    align-items: center;
    flex-wrap: nowrap;
    gap: 12px;
    margin-bottom: 0;
    padding: 0;

    .ant-form-item {
      margin-bottom: 0;
      margin-right: 0;
      flex-shrink: 0;
      display: flex;
      align-items: center;

      :deep(.ant-form-item-label) {
        padding-right: 8px;
        white-space: nowrap;
      }

      :deep(.ant-form-item-control) {
        flex: none;
      }
    }
  }

  .form-actions {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-left: auto;
  }

  .all-actions {
    display: flex;
    align-items: center;
    gap: 24px;
  }

  .search-actions {
    display: flex;
    gap: 8px;
  }

  .operation-actions {
    display: flex;
    gap: 8px;
  }

  :deep(.ant-table-thead > tr > th) {
    background: #fafafa;
    font-weight: 600;
  }

  :deep(.ant-table-tbody > tr:hover > td) {
    background: #f5f5f5;
  }

  // 操作按钮紧凑间距
  :deep(.ant-table-tbody .ant-divider-vertical) {
    margin: 0 4px;
  }

  :deep(.ant-table-tbody .ant-btn-link) {
    padding: 0 4px;
  }

}
</style>
